package com.es.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.es.api.SystemResult;
import com.es.api.exception.OACSException;
import com.es.system.domain.SysResource;
import com.es.system.entity.SysResourceDO;
import com.es.system.mapper.SysResourceMapper;
import com.es.system.service.SysResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 系统资源 服务实现类
 * </p>
 *
 * @author everysucceed
 * @since 2021-12-10
 */
@Service
public class SysResourceServiceImpl extends ServiceImpl<SysResourceMapper, SysResourceDO> implements SysResourceService {
    @Override
    public SystemResult<List<SysResource>> page(Integer page, Integer limit, SysResource sysResource) {
        Page<SysResourceDO> iPage = new Page<>(page, limit);
        iPage = baseMapper.selectPage(iPage, genWrapper(sysResource));
        List<SysResourceDO> list = iPage.getRecords();
        if(list!=null && !list.isEmpty()){
            List<SysResource> data = new ArrayList<>();
            list.forEach(e->{
                SysResource v = new SysResource();
                BeanUtils.copyProperties(e, v);
                //v.setDataEnableTitle(GlobalEnableEnum.getTitleByCode(e.getDataEnable()));
                data.add(v);
            });
            SystemResult result = SystemResult.success(data);
            result.setCount(iPage.getTotal());
            return result;
        }
        return SystemResult.empty("暂无数据");
    }

    @Override
    public SystemResult<Serializable> save(SysResource sysResource) throws OACSException {
        if(sysResource == null){
            throw new OACSException("系统角色不能为空");
        }
        SysResourceDO sysResourceDO = new SysResourceDO();
        BeanUtils.copyProperties(sysResource,sysResourceDO);
        sysResourceDO.setCreateTime(LocalDateTime.now());
        sysResourceDO.setUpdateTime(LocalDateTime.now());
        sysResourceDO.setDataEnable(0);
        baseMapper.insert(sysResourceDO);
        return SystemResult.success(sysResourceDO.getDataId());
    }

    /**
     * @param sysResource 生成动态sql
     * @return
     */
    private LambdaQueryWrapper<SysResourceDO> genWrapper(SysResource sysResource) {
        if(sysResource == null){
            return  null;
        }
        LambdaQueryWrapper<SysResourceDO> wrapper =  Wrappers.lambdaQuery(SysResourceDO.class);
        if(sysResource.getDataId()!=null){
            wrapper.eq(SysResourceDO::getDataId, sysResource.getDataId());
        }
        return wrapper;
    }
}
